<?php
class ModelApiInventory extends Model {
    //获取物流中心默认的发货仓的基本信息
    public function getIL($warehouseId, $type) {
        $ret = array();
        $condList = array(
            'vendor' => array(
                'table' => ' LEFT JOIN `vendor` AS V ON (V.`vproduct_id`=POV.`product_id`) ',
                'cond' => 'V.`vendor`',
            ),
            'pCode' => array(
                'table' => '',
                'cond' => 'POV.`product_code`',
            )
        );
        if ('all' != strtolower($type)) {
            $cList = $tList = array();
            $sql = "SELECT `cond_col`,`cond_val`,`cond_type` FROM `warehouse_special_products` WHERE `warehouse_id`='".$warehouseId."'";
            $res = $this->db->query($sql);
            foreach ($res->rows as $row) {
                if (array_key_exists($row['cond_col'], $condList)) {
                    if ($condList[$row['cond_col']]['table']) {
                        $tList[$condList[$row['cond_col']]['table']] = 1;
                    }
                    $cList[$row['cond_type']][] = $condList[$row['cond_col']]['cond'].((1 == $row['cond_type'])?'=':'<>').$row['cond_val'];
                }
            }
            if (count($cList[1])) {
                $cList[2][] = '('.implode(' OR ', $cList[1]).')';//OR拼接所有等于的条件，然后合并到不等于的数组
            }
            $cList[2][] = 'POV.`product_code`=`inventory`.`product_code`';
            $specialCondition = " AND EXISTS (SELECT `product_code` FROM `product_option_value` AS POV ".implode(' ', array_keys($tList))." WHERE ".implode(' AND ', $cList[2]).")";
        }
        $sql = "SELECT `product_code`,`available_quantity` FROM `inventory` WHERE `warehouse_id`='".$warehouseId."' AND `available_quantity`>0".$specialCondition;
        $res = $this->db->query($sql);
        foreach ($res->rows as $row) {
            $ret[$row['product_code']] = $row['available_quantity'];
        }
        return $ret;
    }

    //暂时缺少库存锁，极端情况下会导致负库存
    public function reduceQtyForSO($warehouseId, $productCode, $qty, $outId, $userId) {
        $sql = "SELECT `id`,`available_quantity` FROM `".DB_PREFIX."inventory` WHERE warehouse_id = '".$warehouseId."' AND product_code = '".$productCode."'";
        $res = $this->db->query($sql);
        if ($res->row['id']) {
            $sql = "UPDATE `inventory` SET `available_quantity`=`available_quantity`-".$qty." WHERE `id`='".$res->row['id']."'";
            $this->db->query($sql);
            //获取商品状态和库存，如果是清仓商品，库存为0，直接下架。
            $available_quantity = $res->row['available_quantity']-$qty;
            if ($available_quantity<=0) {
                $proCode = substr($productCode,0,10);
                $clearance=M('product')->where(array('product_code'=>$proCode))->getField('clearance');
                if ($clearance==1) {
                    M('product')->where(array('product_code'=>$proCode))->save(array('status'=>0));
                }

            }

            $inventoryHistoryData = array(
                'inventory_id'  => $res->row['id'],
                'product_code'  => $productCode,
                'warehouse_id'  => $warehouseId,
                'account_qty'   => 0,//财务数量变更（正+ 负-）
                'available_qty' => (int)(0 - $qty),//可用数量变更（正+ 负-）
                'comment'       => '出库单：'.$outId.' 出库单生成。',//备注（入库单完成、损益单完成、出库单生成、出库单修改、出库单作废）
                'user_id'       => $userId,//操作人PK
                'date_added'    => date('Y-m-d H:i:s'),//条目创建时间
            );

            M('inventory_history')->data($inventoryHistoryData)->add();
        }
    }
}
